
const app = getApp()
import {
  getInfo,
} from '../../../api/member'
import {
  unReadCount,
} from '../../../api/msgPush'
import {
  couponCount
} from '../../../api/coupon'
import {
  traceCount
} from '../../../api/trace'
import {
  favoritesCount
} from '../../../api/favorite'
import {
  summary
} from '../../../api/giftCard'
import {
  getInfo as mchGetInfo
} from '../../../api/enterprise'
import {
  getVIP
} from '../../../api/superVip'
import {
  createQrcode
} from '../../../api/member'
import css2canvas from "../../../utils/css2canvas"
import { update } from '../../../api/user'
import { list as adList } from '../../../api/ad'
import { list as tagList } from '../../../api/tag'
const util = require('../../../utils/util')

Page({
  data: {
    noToken: true,
    name: "微信用户",
    vip: null,
    giftNumber: '',
    cardBalance: 0,//会员卡余额
    favoriteNum: 0, //收藏数
    footprint: 0, //足迹
    couponNum: 0, //优惠券数量
    statusBarHeight: "", //顶部的 高度
    avatar: "", //头像链接
    unReadNum: 0, //未读消息数
    showUnReadNum: "", //显示的未读数量
    mch: null,
    point: '',
    codeType: false,
    qrcode: '',
    qrCodeImg: '',
    canvasType: false,
    cardInfo: {
      TagText: "****", //标签
      Name: '****', //姓名
      avater: "", //需要https图片路径
      qrCode: "", //需要https图片路径
      price: '**',
      logo: 'http://cdnx.rzico.com/images/canvasMyLogo.png',
      coupons: '',
      marketPrice: '',
      activityPrice: ''
    },
    canvasHeight: 400,
    canvasH: 0,
    carvasQrCode: '',
    carvasLogo: '',
    vipMemo: [],
    SCOPE_TYPE: app.SCOPE_TYPE,
    GIFT_TYPE: app.GIFT_TYPE,
    tabbarHeight: app.globalData.tabbarHeight,
    mobile: '',
    mineAd: ''
  },

  onLoad: function () {
    let info = wx.getSystemInfoSync()
    this.data.canvasH = (wx.getSystemInfoSync().windowWidth / 750).toFixed(2)
    this.data.canvasHeight = 500 * this.data.canvasH

    this.setData({
      VERSION: app.VERSION,
      statusBarHeight: app.globalData.statusBarHeight,
      canvasHeight: this.data.canvasHeight,
      // mineAd: util.thumbnail('http://cdnx.rzico.com/27797/image/mineAd.png', 710, 160),
    })
    this.createQrcodeClick()
  },

  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }

    if (app.globalData.token != "" && app.globalData.token != null) {
      this.setData({
        noToken: false
      })
    }
    if (app.globalData.token!=null) {
      const { userInfo } = app.globalData
      if (userInfo.hasOwnProperty("avatar")) { //怎么判断是否已经头像授权
        this.setData({
          avatar: userInfo.avatar,
          name: userInfo.nickname,
        })
      }
    }
    // this.getMineAd()
    this.getGift()
    this.getunReadCount()
    this.getcouponCount()
    this.getTraceCount()
    this.getFavoritesCount()
    this.getVIPClick()
    this.getInfo()
    this.getInfoClick()
  },
  stop() {

  },
  getMineAd(e) {
    let params = {}
    tagList({ type: 8, name: '关于我们' }).then(tag => {
      tag.data.data.map(el => {
        if (el.name == '关于我们') {
          adList({ tagIds: el.id, }).then(ad => {
            if (ad.data.data.length > 0) {
              this.setData({
                mineAd: util.thumbnail(ad.data.data[0].thumbnail, 710, 160),
              })
            }
          })
        }
      })

    })
  },
  getNickname: function (e) {
    let params = {}
    params.nickname = e.detail.value
    update(params).then(res => {
      app.globalData.userInfo.name = res.data.nickname
      this.setData({
        name: res.data.nickname,
      })
    })
  },
  chooseavatar(e) {
    this.selectComponent('#uploadAvatar').uploadImg([e.detail.avatarUrl]);
  },
  metaClick(e) {
    let params = {}
    params.avatar = e.detail.images[0]
    update(params).then(res => {
      app.globalData.userInfo.avatar = e.detail.images[0]
      this.setData({
        avatar: res.data.avatar,
      })
    })
  },
  onChooseAvatar(e) {
    let params = {}
    params.avatar = e.detail.avatarUrl
    update(params).then(res => {
      app.globalData.userInfo.avatar = e.detail.avatarUrl
      this.setData({
        avatar: res.data.avatar
      })
      this.canvasClick()
    })
  },
  getGift() {
    if (this.data.GIFT_TYPE == 1) {
      summary().then(res => {
        if (res.type != "logout") {
          this.data.giftNumber = (res.data.mycount + res.data.rvcount)
          this.setData({
            giftNumber: this.data.giftNumber
          })
        }
      })
    }
  },
  getcouponCount() {
    couponCount().then(res => {
      if (res.type == 'success') {
        this.setData({
          couponNum: res.data
        })
      }
    })
  },

  getTraceCount() {
    traceCount().then(res => {
      if (res.type == 'success') {
        this.setData({
          footprint: res.data
        })
      }
    })
  },

  getFavoritesCount() {
    favoritesCount().then(res => {
      if (res.type == 'success') {
        this.setData({
          favoriteNum: res.data
        })
      }
    })
  },

  //获取用户未读信息数量
  getunReadCount() {
    unReadCount().then(res => {
      let unReadNum = 0
      if (res.data.length > 0) {
        res.data.map(item => {
          unReadNum += item.msg_num
        })
      }
      this.setData({
        unReadNum: unReadNum,
        showUnReadNum: unReadNum > 100 ? '...' : unReadNum
      })
    })
  },

  //获取用户信息
  getInfo() {
    var _this = this
    getInfo().then(
      res => {
        // console.log(res)
        if (res.type == 'success') {
          this.setData({
            vip: util.isNull(res.data.member.vipName) ? "vip" + res.data.member.vip : res.data.member.vipName,
            point: res.data.point,
            mobile: res.data.member.mobile,
            cardBalance: res.data.cardBalance == 0 ? 0 : parseFloat(res.data.cardBalance).toFixed(2),
          })
        }
      }
    ).catch(error => {
      console.log(error)
    })
  },

  //检测用户的登录状态
  checkLogin(callback) {
    console.info("全局变量app.globalData--" + JSON.stringify(app.globalData))
    if (app.globalData.token == null) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      if (callback) {
        callback()
      }
    }
  },
  //我的礼卡
  toGiftCard() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/giftCard/giftCard',
      })
    })
  },

  toContractSigning(e) {
    wx.navigateTo({
      url: '/pages/member/contractSigning/contractSigning'
    })
  },
  //分销中心
  toDistribution() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/distribution/distribution',
      })
    })
  },
  //跳转到个人资料的页面
  toPersonInfo: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/personInfo/personInfo',
      })
    })
  },
  //会员卡
  toSaveCard: function (e) {
    if (this.data.qrcodeLogin == true) {
      return;
    }
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/wallet/jumpPage/saveCard/index',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },
  //收藏夹
  toFavorite: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/favorite/favorite',
      })
    })
  },

  //足迹
  toFootprint: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/footprint/footprint',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  //优惠券
  toCoupon: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/coupon/coupon',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })

  },

  //收货地址
  toAddress: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/functions/jumpPage/address/address',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  // 推广中心
  toShareCenter: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/shareCenter/shareCenter',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  // 新手指引
  toNoviceGuide() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/noviceGuide/noviceGuide',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  //常见问题
  toQuestion: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/commonProblem/commonProblem',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },

  //留言咨询
  toConsultation: function (e) {
    this.checkLogin(() => {
      // wx.navigateTo({
      //         url: '/pages/member/consultation/consultation',
      // })
    })
  },

  //消息通知
  toMessage: function (e) {
    this.checkLogin(() => { })
  },

  //系统设置
  toSet: function (e) {
    this.checkLogin(() => { })
  },

  //关于我们
  toUs: function (e) {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/aboutUs/aboutUs',
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    })

  },

  messageClick() {
    this.checkLogin(() => {
      wx.navigateTo({
        url: '/pages/member/message/index',
      })
    })

  },
  toCall() {
    let _this = this
    console.log(this.data.mch);
    if (!util.isNull(this.data.mch.phone)) {
      wx.makePhoneCall({
      phoneNumber: this.data.mch.phone
    })
    }
  },
  getInfoClick() {
    let _this = this
    mchGetInfo({ mchId: app.globalData.mchId }).then( res => {
      console.log(res,'getInfoClick');
        if (res.type == 'success') {
          _this.data.mch = res.data
          _this.setData({
            mch: _this.data.mch
          })
          console.log(_this.data.mch,'getInfoClick');
        }
      }).catch(error => {
      // _this.data.mch = { phone: '13860431130' }
      // _this.setData({
      //   mch: _this.data.mch
      // })
      console.log(error)
    })
  },
  toAmap() {
    var _this = this
    wx.navigateTo({
      url: '/pages/index/amap',
    })
  },
  // 会员
  vipClick() {
    wx.navigateTo({
      url: '/pages/member/vip/myVip',
    })
  },
  getVIPClick() {
    var _this = this
    getVIP().then(
      res => {
        console.log(res)
        if (res.data.vip != null) {

          _this.data.vipMethod = res.data.vip.method;
          _this.data.vipName = res.data.vip.name
          _this.data.vipMemo = res.data.vip.memo.split(/[(\r\n)\r\n]+/);
          _this.data.vipMemo.forEach(function (item, index) {
            if (!item) {
              _this.data.vipMemo.splice(index, 1);
            }
          })
          _this.setData({
            vipName: _this.data.vipName,
            vipMemo: _this.data.vipMemo
          })

        }
      }
    ).catch(error => {
      console.log(error)
    })
  },

  cancelCode() {
    this.data.codeType = !this.data.codeType
    this.setData({
      codeType: this.data.codeType
    })
  },

  canvasClick() {
    var _this = this
    this.data.canvasType = true
    this.data.cardInfo
    wx.getImageInfo({
      src: _this.data.cardInfo.qrCode, //网络图片路径
      success: res => {
        _this.data.carvasQrCode = res.path; //图片临时本地路径
        wx.getImageInfo({
          src: util.proxyImage(app.APP_BASE_API, util.thumbnail('https://rzico.oss-cn-shenzhen.aliyuncs.com/img/fenxiang.png', 400, 400)), //网络图片路径
          success: res => {
            _this.data.carvasLogo = res.path; //图片临时本地路径
            _this.setData({
              canvasType: _this.data.canvasType,
              cardInfo: _this.data.cardInfo
            })
            setTimeout(function () {
              _this.sharePosteCanvas()
            }, 1000)
          }
        })

      }
    })

  },
  saveShareImg: function () {
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'canvas-show',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) { }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: res.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      });
    }, 1000);
  },
  createQrcodeClick() {
    if (app.globalData.token == null) {
      return;
    }
    createQrcode().then(res => {
      this.data.qrcode = res.content
      this.createImageClick()
    }).catch(error => { })
  },

  createImageClick() {
    let data = this.data.qrcode
    this.data.cardInfo.qrCode = app.APP_BASE_API + '/zxing/createImage?mchId=' + app.globalData.mchId + '&data=' + encodeURIComponent(data)
    this.setData({
      cardInfo: this.data.cardInfo
    })
  },
  sharePosteCanvas: function () {
    var _this = this
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    var canvasShow = wx.createCanvasContext("canvas-show")
    let ctx = new css2canvas(canvasShow)
    var canvasForm = [
      {
        type: "roundRect",
        x: 0,
        y: 0,
        width: 550,
        height: 500,
        background: "#ffffff",
        borderWidth: 1,
        borderRadius: 0,
        clip: false
      },
      {
        type: "image",
        imgUrl: _this.data.carvasQrCode,
        x: 20,
        y: 10,
        width: 400,
        height: 400
      },
      {
        type: "image",
        imgUrl: _this.data.carvasLogo,
        x: 60,
        y: 400,
        width: 40,
        height: 40
      },

      {
        type: "text",
        x: 112,
        y: 400,
        width: 320,
        content: '微信扫一扫，进入小程序',
        color: "#666666",
        fontSize: 24,
        textAlign: "left",
        overflow: "warp",
        maxLine: 1,
        lineHeight: 1
      },
      {
        type: "text",
        x: 130,
        y: 440,
        width: 320,
        content: '（邀请码:' + this.data.mobile.substr(this.data.mobile.length - 4) + '）',
        color: "#666666",
        fontSize: 24,
        textAlign: "left",
        overflow: "warp",
        maxLine: 1,
        lineHeight: 1
      },
    ]
    ctx
      .drawingView(canvasForm)
      .then(res => {
        console.log("绘制完成")
        wx.hideLoading();
      })
  },
  cancleCanvasClick() {
    wx.hideLoading();
    this.data.canvasType = false
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        isHide: false
      })
    }
    this.setData({
      canvasType: this.data.canvasType
    })
  },
  myCatchTouch: function () {
    return;
  },
  mineAdLink(){
    wx.navigateTo({
      url: '/pages/functions/jumpPage/joinUs/joinUs',
    })
  }
})
